<?php

session_start();

$pdo = new PDO('mysql:host=127.0.0.1;dbname=monitor;', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
define('PASSWORD', 'admin123456+1s');

function sql_exec($sql, $params = [])
{
    global $pdo;
    $stmt = $pdo->prepare($sql);
    return $stmt->execute($params);
}

function sql_fetch_all($sql)
{
    global $pdo;
    return $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}

function sql_fetch_row($sql)
{
    global $pdo;
    return $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
}

function is_post()
{
    return $_SERVER['REQUEST_METHOD'] = 'POST';
}

function is_login()
{
    return !empty($_SESSION['login']);
}

function set_login()
{
    setcookie('access_token', md5(PASSWORD), time()+86400*365);
    $_SESSION['login'] = 1;
}

function auto_login()
{
    if (!empty($_COOKIE['access_token'])) {
        if ($_COOKIE['access_token'] == md5(PASSWORD)) {
            $_SESSION['login'] = 1;
        }
    }
}

function redirect($action, $params = [])
{
    $qs = http_build_query(array_merge(['action' => $action, $params]));
    header("Location: index.php?{$qs}");
    exit();
}

$action = isset($_GET['action']) ? $_GET['action'] : 'index';

if (!is_login()) {
    auto_login();
}

if (!is_login() && ($action != 'login' && $action != 'upload' && $action != 'client_info')) {
    redirect('login');
}

if (!in_array($action, ['upload', 'login', 'index', 'monitor', 'stop', 'start', 'set_fps', 'client_info'])) {
    header("HTTP/1.1 404 Not Found");
    exit('404');
}

if ($action == 'login') {
    if (is_login()) {
        redirect('index');
    }
    if (is_post()) {
        if($_POST['password'] == PASSWORD) {
            set_login();
            redirect('index');
        }
        $error = '用户不存在或密码错误';
    }
} else if ($action == 'upload') {
    $name = $_GET['name'];
    $session_id = session_id();
    $connect_time = $last_active_time = time();
    $row = sql_fetch_row('select * from client');
    if ($row) {
        $fps = $row['fps'];
        $sql = 'update client set name=:name,last_active_time=:last_active_time where session_id=:session_id';
        $params = [
            ':name' => $name,
            ':last_active_time' => $last_active_time,
            ':session_id' => $session_id
        ];
        sql_exec($sql, $params);
    } else {
        $fps = 3;
        $sql = 'insert client set name=:name,last_active_time=:last_active_time, connect_time=:connect_time, session_id=:session_id, fps=:fps';
        $params = [
            ':name' => $name,
            ':last_active_time' => $last_active_time,
            ':session_id' => $session_id,
            ':connect_time' => $connect_time,
            ':fps' => $fps,
        ];
        sql_exec($sql, $params);
    }

    $path = 'uploads/'.uniqid().'.jpg';
    $upload_time = time();
    move_uploaded_file($_FILES['webcam']['tmp_name'], $path);
    sql_exec('insert image set path=:path,upload_time=:upload_time,session_id=:session_id', [
        ':path' => $path,
        ':upload_time' => $upload_time,
        ':session_id' => session_id(),
    ]);

    $data = [
        'is_stop' => $row['status'] == 2,
        'FPS' => $fps,
    ];

    echo json_encode($data);
    exit();
} else if ($action == 'index') {
    $clients = sql_fetch_all('select * from client where last_active_time>'.(time()-600/*10分钟*/).' order by last_active_time desc');
} else if ($action == 'monitor') {
    $id = $_GET['id'];
    if (!empty($_GET['ajax'])) {
        $client = sql_fetch_row('select * from client where session_id='.$pdo->quote($id));
        $img = sql_fetch_row('select id,path,FROM_UNIXTIME(upload_time) as t from image order by id desc limit 1');
        $data = [
            'client' => $client,
            'img' => $img,
        ];
        echo json_encode($data);
        exit();
    }
} else if ($action == 'stop') {
    $id = $_POST['id'];
    sql_exec('update client set status=2 where session_id=:id', [
        ':id' => $id
    ]);
    exit();
} else if ($action == 'start') {
    $id = $_POST['id'];
    sql_exec('update client set status=1 where session_id=:id', [
        ':id' => $id
    ]);
    exit();
} else if ($action == 'set_fps') {
    $id = $_POST['id'];
    $fps = $_POST['fps'];
    if ($fps <= 0) {
        $fps = 1;
    }
    sql_exec('update client set fps=:fps where session_id=:id', [
        ':id' => $id,
        ':fps' => $fps,
    ]);
    exit();
} else if ($action == 'client_info') {
    $id = session_id();
    $client = sql_fetch_row('select status from client where session_id='.$pdo->quote($id));
    echo !empty($client['status']) ? $client['status'] : 1;
    exit();
}

ob_start();
require "views/{$action}.php";
$__content = ob_get_clean();
require 'views/layout.php';